@extends('layouts.prize')
@section('pageTitle', '奖品管理')
@section('content')

    {{--@component('components.web.sidemenu')--}}
    {{--@endcomponent--}}

    <div class="main-panel">
        <div class="content">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card ">
                            <div class="header">
                                {{--<div class="btn-group" role="group">--}}
                                    {{--<button type="button" class="btn btn-primary" role="1">自建奖品</button>--}}
                                    {{--<button type="button" class="btn btn-primary" role="2">红包奖品</button>--}}
                                {{--</div>--}}
                                {{--<form id="searchForm" class="btn-group" role="search" style="width: 400px" method="get"--}}
                                      {{--onsubmit="return beforeSearch();">--}}
                                    {{--<div class="input-group">--}}
                                        {{--<input type="hidden" id="sourceType" value="">--}}
                                        {{--<input type="text" id="prizeName" value="" style="z-index: 0"--}}
                                               {{--class="form-control" placeholder="Search...">--}}
                                        {{--<span class="input-group-addon"><i class="fa fa-search"></i></span>--}}
                                    {{--</div>--}}
                                {{--</form>--}}
                                <div class="btn-group" role="group" style="float: right!important;">
                                    <a type="button" class="btn btn-primary" href="/web/prize/create">新建奖品</a>
                                </div>
                            </div>
                            <div class="content" id="tableContent">

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--摸态框-->
    <div class="modal fade" id="dynamicModal" tabindex="-1" role="dialog" aria-labelledby="buyprizeModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content detail">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">库存详情</h4>
                </div>
                <div class="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">返回</button>
                    <button type="button" class="btn btn-primary btn-submit">确定</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="staticModal" tabindex="-1" role="dialog" aria-labelledby="buyprizeModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content edit">
                <form method="post" action="">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="modalName">入库</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" value="1" name="prize_id" id="prizeId">
                        <div class="row">
                            <div class="col-sm-8 col-sm-offset-2">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <div class="form-group">
                                            <label id="inputFieldName" class="col-sm-3 control-label">入库数量</label>
                                            <div class="col-sm-8 ">
                                                {{ csrf_field() }}
                                                <input class="form-control wx-input-money"
                                                       type="number"
                                                       number="true"
                                                       name="number"
                                                       placeholder="请输入数量"
                                                       datatype="/^10$|^[1-9][0-9]{0,3}$/"
                                                       id="inputFiled"
                                                >
                                                <input type="hidden" id="remain_num">
                                                <div class="info"><span
                                                            class="Validform_checktip"></span><span
                                                            class="dec"><s class="dec1">&#9670;</s><s class="dec2">&#9670;</s></span>
                                                </div>
                                                <span id="helperName" class="help-block">一次性最多入库10000个</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary btn-submit">确定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="buyprizeModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content delete">
                <form method="post" action="/web/prize/delete">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="modalName">警告</h4>
                    </div>
                    <div class="modal-body">
                        {{ csrf_field() }}
                        <input type="hidden" value="1" name="prize_id" id="deleteId">
                        <div class="row">
                            <div class="col-sm-8 col-sm-offset-2">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <div class="form-group">
                                            <div id="helperName" class="help-block">确认删除奖品&nbsp;
                                                <span id="deleteName"></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary btn-submit">确定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="modal fade" id="codeModal" tabindex="-1" role="dialog" aria-labelledby="buyprizeModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content edit">
                <form method="post" action="/web-api/prize/import-voucher-code" enctype="multipart/form-data">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                                    aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="modalName">导入券码</h4>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" value="1" name="prize_id" id="prizeId">
                        <div class="row">
                            <div class="col-sm-8 col-sm-offset-2">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <form action="/web-api/prize/import-voucher-code" method="post" enctype="multipart/form-data">
                                            <p class="help-block text-danger">每次最多可导入1000个劵码</p>
                                            <p class="help-block text-danger">码劵不能有中文和英文逗号</p>
                                            <div class="form-group">
                                                <input type="hidden" name="prize_id">
                                                <input type="file" name="codes" accept=".csv" class="form-control" id="voucher_code_file" placeholder="劵码文件" required>
                                            </div>
                                            <button type="submit" id="import" class="btn btn-primary">导入</button>
                                            <a class="blue-button" id="export" href="/admin/voucher-code-example.csv" target="_blank">下载券码模板</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary btn-submit">确定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    {{--订单确认模态框--}}
    @component('web.prizePayment.payModel')
    @endcomponent
@endsection
@section('style')
    <link rel="stylesheet" href="/css/admin/validform_style.css">
    <style>
        .blue-button, .small-blue-button {
            text-align: center;
            outline: 0;
            display: inline-block;
            padding: 7px 16px;
            color: #fff;
            background-color: #23CCEF;
            border: 1px solid #23CCEF;
            margin: 0 5px;
            font-size: 14px;
            -webkit-border-radius: 4px;
            -moz-border-radius: 4px;
            -ms-border-radius: 4px;
            -o-border-radius: 4px;
            border-radius: 4px;
            min-width: 110px;
        }
        .blue-button:hover, .small-blue-button:hover {
            background-color: #11bfe3;
            color: #FFF;
        }
    </style>
    <style>
        .dropdown-menu:before, .dropdown-menu:after {
            display: none;
        }

        .modify-modal {
            width: 80%;
        }

        .modify-modal label {
            font-weight: normal;
        }

        #searchForm .input-group-addon {
            cursor: pointer;
        }
    </style>
@endsection()
@section('script')
    <script src="/js/admin/Validform_v5.3.2_min.js"></script>
    <script src="/js/initValidform.js"></script>
    <script>
		function beforeSearch() {
			var resourceType = $('input#sourceType').val();
			var search = $('input#prizeName').val();
			queryTable(resourceType, search);
			return false;
		}
		function queryTable(resourceType, search) {
			$.get('/web/prize/query?resource=' + resourceType + '&name=' + search, function (res) {
				$('#tableContent').html(res);
			});
		}
		$(document).on('click', '.operate-btn', function () {
			var prizeId = $(this).closest('.operate-group').attr('id');
			if ($(this).hasClass('entry')) {
				$('#staticModal').find('#prizeId').val(prizeId);
				$('#staticModal').find('#inputFiled').val('');
                $('#staticModal').find('#remain_num').val('');
				$('#staticModal').find('form').attr('action', '/web/prize/entry');
				$('#staticModal').find('#modalName').text('入库');
				$('#staticModal').find('#inputFieldName').text('入库数量');
				$('#staticModal').find('#helperName').text('一次性最多入库10000个');
				$('#staticModal').modal();
				initValidform($('#staticModal').find('form'));
			} else if ($(this).hasClass('detail')) {
				$('#dynamicModal').find('.modal-title').text('库存详情');
				$('#dynamicModal').find('button.btn-submit').hide();
				$('#dynamicModal').find('.modal-dialog').removeClass('modify-modal');
				$.get('/web/prize/detail?prize_id=' + prizeId, function (res) {
					$('#dynamicModal').find('.modal-body').html(res);
					$('#dynamicModal').modal();
				});
			} else if ($(this).hasClass('delivery')) {
				$('#staticModal').find('#prizeId').val(prizeId);
				$('#staticModal').find('#inputFiled').val('');
				$('#staticModal').find('form').attr('action', '/web/prize/delivery');
				$('#staticModal').find('#modalName').text('出库');
				$('#staticModal').find('#inputFieldName').text('出库数量');
                $.get('/web/prize/availablePrize?prize_id=' + prizeId, function (res) {
                    var availableNumber = 10000;
                    if(res.code==0){
                        availableNumber = res.availableNumber;
                        $('#staticModal').find('#helperName').text('一次性最多出库'+availableNumber+'个');
                        $('#staticModal').find('#inputFiled').attr('datatype',"/^"+availableNumber+"$|^[1-9][0-9]{0,3}$/");

                    }
                    $('#staticModal').find('#remain_num').val(availableNumber);
                });
				$('#staticModal').modal();
				initValidform($('#staticModal').find('form'));
			} else if ($(this).hasClass('modify')) {
				location.href = '/web/prize/modify?prize_id=' + prizeId;
				return;
				$('#dynamicModal').find('.modal-title').text('编辑');
				$('#dynamicModal').find('button.submit').show();
				$('#dynamicModal').find('.modal-dialog').addClass('modify-modal');
				$.get('/web/prize/modify?prize_id=' + prizeId, function (res) {
					$('#dynamicModal').find('.modal-body').html(res);
					$('#dynamicModal').modal();
					initValidform($('#dynamicModal').find('#wizardForm'));
					$('#dynamicModal').find('button.btn-submit').on('click', function () {
						$(this).closest('.modal-content').find('form').submit();
					});
				});
			} else if ($(this).hasClass('delete')) {
				var deleteName = $(this).closest('tr').find('td').first().text();
				$('#deleteId').val(prizeId);
				$('#deleteName').text(deleteName);
				$('#deleteModal').modal();
				$('#deleteModal').find('.btn-submit').on('click', function () {
					$('#deleteModal').find('form').submit();
					$('#deleteModal').modal('hide');
				})
			} else if ($(this).hasClass('pay')) {
				var orderID = $(this).closest('tr').find('.order_id').val();
				$.get('/payment/payment/check', {'order_id': orderID}, function (res) {
					$('#checkModal').find('.modal-footer').find('.btn-primary ').removeAttr('disabled');
					$('#checkModal').find('.modal-body').html(res);
					$('#checkModal').modal({'backdrop': 'static'});
					orderId = $('#checkModal').find('.modal-body').find('.order_id').text();
				})
				payModal('index');
			}else if($(this).hasClass('import')){
                var $codeModal = $('#codeModal');
                $('#codeModal input[name=prize_id]').val(prizeId);
                $('#codeModal').modal();
                $('#import').click(function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    var $this = $(this);
                    if(!$this.hasClass('disabled')){
                        $this.addClass('disabled');
//                        $(this).parents('form').submit();
                        var $form = $(this).parents('form');
                        var $file = $form.find('#voucher_code_file');
                        console.log('测试');
                        if($file[0].files.length>0){
                            $.ajax({
                                type: "POST",
                                url: "/web-api/prize/import-voucher-code",
                                processData: false,
                                contentType: false,
                                data: new FormData($form[0]),
                                cache: false,
                                async: false,
                                success: function (data) {
                                    setTimeout(function(){
                                        $this.removeClass('disabled');
                                    },1000);
                                    if(data.code == 200){
                                        utils.showNotification('上传成功',2);
                                        $codeModal.modal('hide');
                                        top.loadContent.location.reload();
                                    }else{
                                        utils.showNotification(data.message, 4);
                                    }
                                },
                                error: function (XMLHttpRequest, textStatus, errorThrown) {
                                    alert("上传失败，请检查网络后重试");
                                    $this.removeClass('disabled');
                                }
                            });
                        }else{
                            utils.showNotification('请选择文件上传', 3);
                            $this.removeClass('disabled');
                        }
                    }
                });
            }
		});
		$(document).ready(function () {
			queryTable('', '');
			$('.header').find('button').on('click', function () {
				var resourceType = $(this).attr('role');
				$('input#sourceType').val(resourceType);
				beforeSearch();
			});
			initValidform($('#deleteModal').find('form'));
			$('#tableContent').on('click', 'ul.pagination a', function () {
				$.get($(this).attr('href'), function (res) {
					$('#tableContent').html(res);
				});
				return false;
			});
			$('#searchForm').find('.input-group-addon').on('click', function () {
				$('#searchForm').submit();
			});
		})

        function initValidform(formObj) {
            return formObj.Validform({
                btnSubmit: ".btn-submit",
                postonce: true,
                ajaxPost: true,
                datatype: {
                    sponsor: function (gets, obj, curform, regxp) {
                        if (gets.length == 0) {
                            return false;
                        }
                        var ZhCount = 0
                        var OtCount = 0
                        for (var a = 0; a < gets.length; a++) {
                            var asc = gets.charCodeAt(a)
                            if (asc > 127) {
                                ZhCount++
                            } else {
                                OtCount++
                            }
                        }
                        if ((ZhCount * 4 + OtCount * 1) > 32) {
                            return '只能输入8个中文字符或32个英文字符';
                        } else {
                            return true;
                        }
                    }
                },
                tiptype: function (msg, o, cssctl) {
                    if (!o.obj.is("form")) {//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
                        var objtip = o.obj.closest('.form-group').find(".Validform_checktip");
                        cssctl(objtip, o.type);
                        objtip.text(msg);
                        var infoObj = o.obj.closest('.form-group').find(".info");
                        if (o.type == 2) {
                            infoObj.fadeOut(200);
                        } else {
                            if (infoObj.is(":visible")) {
                                return;
                            }
                            var left = o.obj.position().left + 130,
                                top = o.obj.get(0).top;
                            infoObj.css({
                                // "left": left,
                                "margin-top": top
                            }).show().animate({
                                "margin-top": "10px"
                            }, 200);
                        }
                    }
                },
                beforeCheck: function (curform) {
                    //在表单提交执行验证之前执行的函数，curform参数是当前表单对象。
                    //这里明确return false的话将不会继续执行验证操作;
                },
                beforeSubmit: function (curform) {
                    var delevery_num = parseInt($(curform).find('#inputFiled').val());
                    var remain_num = parseInt($(curform).find('#remain_num').val());
                    if(!isNaN(remain_num) && remain_num <= 0 ) {
                        alert('无可用库存');
                        return false;
                    }
                    if(!isNaN(remain_num) && delevery_num > remain_num){
                        alert('出库数量不能大于最大出库数量');
                        return false;
                    }
                    //在验证成功后，表单提交前执行的函数，curform参数是当前表单对象。
                    //这里明确return false的话表单将不会提交;
                },
                callback: function (data) {
                    if (data.code == 0) {
                        location.href = data.result;
                    } else {
                        utils.showNotification(data.result, 3);
                    }
                    //返回数据data是json对象，{"info":"demo info","status":"y"}
                    //info: 输出提示信息;
                    //status: 返回提交数据的状态,是否提交成功。如可以用"y"表示提交成功，"n"表示提交失败，在ajax_post.php文件返回数据里自定字符，主要用在callback函数里根据该值执行相应的回调操作;
                    //你也可以在ajax_post.php文件返回更多信息在这里获取，进行相应操作；
                    //ajax遇到服务端错误时也会执行回调，这时的data是{ status:**, statusText:**, readyState:**, responseText:** }；
                    //这里执行回调操作;
                    //注意：如果不是ajax方式提交表单，传入callback，这时data参数是当前表单对象，回调函数会在表单验证全部通过后执行，然后判断是否提交表单，如果callback里明确return false，则表单不会提交，如果return true或没有return，则会提交表单。
                }
            });
        }
    </script>
@endsection()
